﻿using System;
using System.Web;
using System.IO;
using NVelocity;
using NVelocity.App;
using NVelocity.Context;
using NVelocity.Runtime;
using Commons.Collections;
 
/// <summary>
/// NVelocity模板工具类 VelocityHelper
/// </summary>
namespace Enterprise.Web
{
    public class VelocityHelper {
        private VelocityEngine velocity = null;
        private IContext context = null;
        private System.Text.Encoding _encoding ;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="templatDir">模板文件夹路径</param>
        public VelocityHelper(string templatDir,  System.Text.Encoding encoding) {
            Init(templatDir, encoding  );
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="templatDir">模板文件夹路径</param>
        public VelocityHelper(string templatDir) {
            Init(templatDir, System.Text.Encoding.Default);
        }


        /// <summary>
        /// 无参数构造函数
        /// </summary>
        public VelocityHelper() {
            ;
        }

        /*
        /// <summary>
        /// 初始话NVelocity模块
        /// </summary>
        /// <param name="templatDir">模板文件夹路径</param>
        public void Init(string templatDir) {
            //创建VelocityEngine实例对象
            velocity = new VelocityEngine();

            //使用设置初始化VelocityEngine
            ExtendedProperties props = new ExtendedProperties();
            props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, HttpContext.Current.Server.MapPath(templatDir));
            props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
            props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");
            velocity.Init(props);

            context = new VelocityContext();
        }*/

        public void Init(string templatDir, System.Text.Encoding encoding) {
            this._encoding = encoding;
            //创建VelocityEngine实例对象
            velocity = new VelocityEngine();

            //使用设置初始化VelocityEngine
            ExtendedProperties props = new ExtendedProperties();
            props.AddProperty(RuntimeConstants.RESOURCE_LOADER, "file");
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, HttpContext.Current.Server.MapPath(templatDir));
            props.AddProperty(RuntimeConstants.INPUT_ENCODING, encoding.WebName);
            props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, encoding.WebName);
            velocity.Init(props);

            context = new VelocityContext();

            //初始化模板内使用的工具
            InitTemplatePageHelper();
        }

        /// <summary>
        /// 初始化模板内使用的工具
        /// </summary>
        public void InitTemplatePageHelper() {
            Put("helper", new TemplatePageHelper());
        }

        /// <summary>
        /// 给模板变量赋值
        /// </summary>
        /// <param name="key">模板变量</param>
        /// <param name="value">模板变量的值</param>
        public void Put(string key, object value) {
            if (context == null)
                context = new VelocityContext();
            context.Put(key, value);
        }

        /// <summary>
        /// 显示模板
        /// </summary>
        /// <param name="templatFileName">模板文件</param>
        public void Display(string templatFileName) {
            //从文件中读取模板
           NVelocity.Template template = velocity.GetTemplate(templatFileName);
            //合并模板
            StringWriter writer = new StringWriter();
            template.Merge(context, writer);
            //输出
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(writer.ToString());
            HttpContext.Current.Response.Flush();
            //HttpContext.Current.Response.End();
        }

        /// <summary>
        /// 保存到文件
        /// </summary>
        /// <param name="templatFileName">模板文件</param>
        public void SaveAs(string templatFileName, string fileName) {
            //从文件中读取模板
            NVelocity.Template template = velocity.GetTemplate(templatFileName);
            //合并模板
            StringWriter writer = new StringWriter();
            template.Merge(context, writer);
            //输出
            SaveFile(writer.ToString(), fileName, false );
        }

       
        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="sw"></param>
        /// <param name="fileName"></param>
        private void SaveFile(string str, string fileName, bool append) {
            if (string.IsNullOrEmpty(fileName))
                throw new Exception("fileName is Null ErrCode=0!");

            string dir = System.IO.Path.GetDirectoryName(fileName);
            if (!System.IO.Directory.Exists(dir)) {
                System.IO.Directory.CreateDirectory(dir);
            }


            byte[] allData = this._encoding.GetBytes(str);
            FileStream fileStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite, FileShare.None, 1024,false);
            try {
                foreach (var btD in allData) {
                    fileStream.WriteByte(btD);
                }
            } catch {
                throw new Exception("SaveTempPageEx");//ex
            } finally {
                fileStream.Close();
                fileStream.Dispose();
            }
            
            /*
            StreamWriter streamWriter = new StreamWriter(fileName, append, this._encoding);
            try {
                streamWriter.Write(str);
            } catch {

            } finally {
                streamWriter.Close();
                streamWriter.Dispose();
            }
             * */
        }
    }
}